const Router = require('koa-router'),
	mongoose = require('mongoose')

let router = new Router()

router.get('/', async ctx => {
	ctx.body = '用户操作首页'
})

router.post('/register', async ctx => {
	const User = mongoose.model('User')

	let newUser = new User(ctx.request.body)
	console.log(newUser)

	await newUser
		.save()
		.then(() => {
			ctx.body = {
				code: 200,
				message: 'successfully register'
			}
		})
		.catch(error => {
			ctx.body = {
				code: 500,
				message: error
			}
		})
})

router.post('/login', async ctx => {
	const User = mongoose.model('User'),
		loginUser = ctx.request.body,
		userName = loginUser.userName,
		password = loginUser.password

	await User.findOne({ userName: userName })
		.exec()
		.then(async result => {
			if (result) {
				const user = new User()

				await user
					.comparePassword(password, result.password)
					.then(isMatch => {
						ctx.body = {
							code: 200,
							message: isMatch
						}

						User.update(
							{ userName: userName },
							{ $set: { lastLoginAt: new Date() } }
						).exec()
					})
					.catch(error => {
						ctx.body = {
							code: 500,
							message: error
						}
					})
			} else {
				ctx.body = {
					code: 500,
					message: '用户名不存在！'
				}
			}
		})
		.catch(error => {
			ctx.body = {
				code: 500,
				message: error
			}
		})
})

module.exports = router
